package com.prs.crm.report;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Logger;

import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

/**
 * PDF导出
 * @author prs.chenzhi
 *
 */
public class PdfExport implements ReportExport{
	
	private static final Logger log = Logger.getLogger(PdfExport.class);
	
	public PdfExport()
	{
	
	}

	public void export(ReportTable table,String out,ExportConfig config)
	{

		Document doc =  new Document(PageSize.A4);
		OutputStream streamOut = null;
		try
		{
			streamOut = new FileOutputStream(out);
			PdfWriter 	writer = PdfWriter.getInstance(doc, streamOut);
			doc.open();
			prepareDraw(writer,doc,table.getName());
			doc.add( renderTable(table,config));
		}
		catch (Exception e)
		{
			log.error(e);
			e.printStackTrace();
		}
		finally
		{
			doc.close();
		}
	}
	
	/**
	 * 绘制准备
	 * @param writer
	 * @param doc
	 */
	private void prepareDraw(PdfWriter writer,Document doc,String title) throws Exception
	{
		Paragraph para = new Paragraph(title,new Font(getChineseBaseFont(),10f,Font.BOLD));
		para.setIndentationLeft(-40f);
		para.setAlignment(Element.ALIGN_CENTER);
		doc.add(para);
		
		//draw line
		float pageHeight = doc.getPageSize().getHeight();
		float x = 81f;
		float y = pageHeight - 68f;
		drawLine(writer,x, y);
	}
	
	/**
	 * 生成PdfPTable
	 * @param table
	 * @param config
	 * @return
	 */
	private PdfPTable renderTable(ReportTable table,ExportConfig config)
	{
		PdfPTable pt = new PdfPTable(table.getCells().size());
		pt.setWidthPercentage(100);
		Font font = getFont(config.getFontSize());
		Font headFont =  getFont(config.getFontSize());
		headFont.setStyle(Font.BOLD);
		/**
		 * 绘制表头
		 */
		for (ReportCell cell : table.getCells())
		{
			pt.addCell(getPCell(cell.getName(),headFont,cell,config));
		}
		
		/**
		 * 绘制表身
		 */
		for (Object data : table.getDataSource())
		{
			for (ReportCell cell : table.getCells())
			{
				if(cell.getMap() != null){
					String key = ReportUtils.getValue(data, cell.getProperty(), cell.getFormat());
					String value = !key.equals("") ? cell.getMap().get(key.trim()).toString() : cell.getMap().get("null") == null ? "" : cell.getMap().get("null");
					pt.addCell(getPCell(value,font,cell,config));
				}else if(cell.getSuffix() != ' '){
					char suffix = cell.getSuffix();
					String value = ReportUtils.getValue(data, cell.getProperty(), cell.getFormat());
					value = value.equals("") ? value : value + suffix;
					pt.addCell(getPCell(value,font,cell,config));
				}else{
					pt.addCell(getPCell(ReportUtils.getValue(data, cell.getProperty(), cell.getFormat()),
							font,cell,config));
				}
			}
		}
		
		return pt;
	}
	
	private PdfPCell getPCell(String value, Font font,ReportCell cell,ExportConfig config){
		PdfPCell pc = new PdfPCell();
		Paragraph chun = new Paragraph(value,font);
		pc.addElement(chun);
		pc.setUseAscender(true);
		pc.setVerticalAlignment(Cell.ALIGN_MIDDLE);
		pc.setHorizontalAlignment(getCellAlign(cell.getAlign()));      
		pc.setBackgroundColor(cell.getBackgroundColor());
		pc.setBorderColor(cell.getBorderColor());
		pc.setBorderWidth(config.getBorderWidth());
		pc.setFixedHeight(config.getFixedHeight());
		return pc;
	}
	
	private void drawLine(PdfWriter writer,float x, float y) {
		PdfContentByte dc = writer.getDirectContent();
		dc.setLineWidth(0.1f);
		dc.setGrayStroke(0f);
		dc.moveTo(x, y);
		dc.lineTo(x + 200f, y);
		dc.stroke();
	}
	
	private Font getFont(float fontsize){
		try {
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); 
			Font titleFont= new Font(bfChinese, fontsize, Font.NORMAL);
			return titleFont;
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private BaseFont getChineseBaseFont(){
		try {
			return BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public int getCellAlign(int align)                                                                                    
	  {                        
		switch (align)
		{
			case ReportCell.ALIGN_LEFT:return Cell.ALIGN_LEFT;
			case ReportCell.ALIGN_CENTER:return Cell.ALIGN_CENTER;
			case ReportCell.ALIGN_RIGHT:return Cell.ALIGN_RIGHT;
			default:return Cell.ALIGN_CENTER;
		}                                                                                  
	  }
/**
 * 销售订单
 */
	public void exportSaleOrder(ReportTable table, String out,
			ExportConfig config) {
		// TODO Auto-generated method stub
		
	}

public void exportAlreadyDistribution(ReportTable table, String out,
		ExportConfig config) {
	// TODO Auto-generated method stub
	
}    
	
}
